import ReactDOM from 'react-dom';
import React, { useEffect, useState } from 'react';
import 'babel-polyfill';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import 'braft-editor/dist/index.css';

import { LazyLoad, KeepAlive, CProps } from '@/components/Index';

import { routes } from '@/router/admin';
import { getHash } from '@/utils/public';
import { setStore, connect } from '@/state/Connect';

import '@/index.global.less';
import './admin.less';

import '@/utils/adaptation';

// 热更新
if (module?.hot) {
  module.hot.accept();
}

// window.local_prefix = 'http://192.0.20.21:3001';

export const renderRoute = (list: any[], num: number, isKeepAlive?: (item: any) => boolean) => {
  return list.map((item) => {
    const children = item.children || [];
    let childrenRoutes: any = [];
    if (children.length > 0) {
      childrenRoutes = renderRoute(children, num + 1);
    }

    let keep = item.keepAlive;
    if (isKeepAlive) {
      keep = isKeepAlive(item);
    }

    return (
      <KeepAlive keepAlive={keep} key={item.path} routePath={item.path}>
        <LazyLoad routeData={item} loadComponent={item.component} routes={childrenRoutes} routeList={children}></LazyLoad>
      </KeepAlive>
    );
  });
};

const Root = () => {
  useEffect(() => {
    if (getHash() === '/' || !getHash()) {
      window.location.hash = '/index';
    }
    // 判断是否登录
    if (localStorage.getItem('currentUser')) {
      const dataStr = localStorage.getItem('currentUser');
      try {
        const data = JSON.parse(dataStr) || {};
        setStore({ currentUser: data });
      } catch (error) {
        console.error(error);
      }
    }
  }, []);

  return <>{renderRoute(routes, 0)}</>;
};

ReactDOM.render(
  <ConfigProvider locale={zh_CN}>
    <Root></Root>
  </ConfigProvider>,
  document.getElementById('root')
);
